package com.xliu.cs.openprojects.videoplay.controller;

import com.xliu.cs.openprojects.videoplay.in_out.FileInfo;
import com.xliu.cs.openprojects.videoplay.util.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@RequestMapping("/file")
@Controller
public class FileController {


    @GetMapping("/list")
    @ResponseBody
    public List<FileInfo> listFiles(@RequestParam(required = false) String rootPath) {
        System.out.println("rootPath: is " + rootPath);
        File[] childs;
        if (rootPath == null) {
            childs = File.listRoots();
        } else {
            childs = new File(rootPath).listFiles();
        }

        if (childs == null) {
            return Collections.emptyList();
        }

        return Arrays.stream(childs).map(f -> {
            try {
                return new FileInfo(f.isDirectory(), f.getCanonicalPath(), FileUtils.getFileType(f));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }).sorted((fa, fb) -> {
          if (fa.isDir() && fb.isDir()) {
              return fa.getPath().compareTo(fb.getPath());
          }
          if (fa.isDir()) {
              return -1;
          }
          return 1;
        }).collect(Collectors.toList());
    }
}
